package com.glq1218.authentication.filter;

import com.glq1218.authentication.model.AuthenticatedUser;
import com.glq1218.common.util.JwtUtils;
import com.glq1218.common.util.RedisUtils;
import com.glq1218.common.util.ServletUtils;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 自定义jwt过滤器
 *
 * @author glq1218
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain
    ) throws ServletException, IOException {
        final String authHeader = request.getHeader("Authorization");
        final String jwt;
        final String username;
        String requestRri = request.getRequestURI();
        if (requestRri.startsWith("/api/auth/")) {
            doFilter(request, response, filterChain);
            return;
        }
        // 请求头中没有认证信息或者认证信息不正确
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            filterChain.doFilter(request, response);
            return;
        }
        jwt = authHeader.substring(7);
        // token是否能成功解析出用户名
        try {
            username = JwtUtils.getUsername(jwt);
        } catch (JwtException e) {
            log.error("用户使用了错误的令牌：{}", jwt);
            ServletUtils.sendMsg(response, 401, "token令牌错误");
            return;
        }

        // token是否过期
        if (JwtUtils.isExpired(jwt)) {
            log.error("IP地址为：{}，的用户使用了过期的令牌：{}", ServletUtils.getIpAddress(request), jwt);
            ServletUtils.sendMsg(response, 401, "token过期");
            return;
        }
        // 判断redis中是否过期
        var expire = redisUtils.getExpire("loginUser:" + username + ":" + jwt);

        // 如果还剩十分钟过期，就延长过期时间
        if (expire <= 60 * 10) {
            redisUtils.setExpire("loginUser:" + username, 12, TimeUnit.HOURS);
            log.info("用户：{}，的令牌：{}，延期了十分钟", username, jwt);
        }
        AuthenticatedUser authenticatedUser = redisUtils.get("loginUser:" + username + ":" + jwt, AuthenticatedUser.class);
        if (Objects.isNull(authenticatedUser)) {
            log.warn("用户：{}，登录过期", username);
            ServletUtils.sendMsg(response, 401, "登录过期，请重新登录");
            return;
        }
        UsernamePasswordAuthenticationToken authenticated = UsernamePasswordAuthenticationToken.authenticated(
                authenticatedUser,
                null,
                authenticatedUser.getAuthorities()
        );
        authenticated.setDetails(
                new WebAuthenticationDetailsSource().buildDetails(request)
        );
        SecurityContextHolder.getContext().setAuthentication(authenticated);
        log.debug("set Authentication to security context for '{}', uri: {}", authenticated.getName(), requestRri);
        filterChain.doFilter(request, response);
    }
}
